package binaryTree;

import java.util.ArrayList;
import java.util.List;
public class BinaryTree {
    //手动创建一个二叉树
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }


    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    //前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //将前序遍历的结果 存储到list当中
    public List<TreeNode> preOrder2(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();

        if(root == null) return list;

        list.add(root);

        List<TreeNode> leftTree = preOrder2(root.left);
        list.addAll(leftTree);

        List<TreeNode> rightTree = preOrder2(root.right);
        list.addAll(rightTree);

        return list;
    }

    //中序遍历
    public List<TreeNode> inorderTraversal(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        if (root == null) return list;

        List<TreeNode> leftTree = inorderTraversal(root.left);
        list.addAll(leftTree);

        list.add(root);

        List<TreeNode> rightTree = inorderTraversal(root.right);
        list.addAll(rightTree);

        return list;
    }

    //后序遍历
    public List<TreeNode> postorderTraversal(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        if (root == null) return list;

        List<TreeNode> leftTree = postorderTraversal(root.left);
        list.addAll(leftTree);

        List<TreeNode> rightTree = postorderTraversal(root.right);
        list.addAll(rightTree);

        list.add(root);

        return list;
    }

    //节点个数
    public int size(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }

    //算个数
    public boolean find(TreeNode root, char key) {
        if(root == null) {
            return false;
        }

        if(root.val == key) {
            return true;
        }

        return false;
    }

}
